<template>
	<view class="container">		
		<view class="cu-card article no-card padding-top-xs">
			<view class="cu-item shadow padding-top">
				<view class="content">
					<view class="desc">
						<view>{{ chooseAddress.houseName }}</view>
						<view class="padding-top-xs text-grey">{{ chooseAddress.address }} {{ chooseAddress.realName }}  {{ chooseAddress.phone }}</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="bg-white pt-30 mb-20">
			<view class="font-size-medium font-weight-bold mb-30 pl-30">商品列表</view>
			<list-cell arrow line-right>
				<view class="w-100 d-flex align-items-center overflow-hidden">
					<scroll-view class="flex-fill overflow-hidden" scroll-x>
						<view class="w-100 d-flex align-items-center">
							<image :src="item.image" class="pro-img" v-for="(item, index) in cart" :key="index"></image>
						</view>
					</scroll-view>
					<view class="flex-shrink-0 ml-20">共{{ cartNum }}件</view>				
				</view>
			</list-cell>
			<list-cell arrow last>
				<view class="w-100 d-flex align-items-center justify-content-between">
					<view class="d-flex align-items-center">
						<view>水卷</view>
						<view class="coupon-label">劵</view>
					</view>
					<view class="text-color-assist">敬请期待</view>
				</view>
			</list-cell>
			<list-cell arrow last>
				<view class="w-100 d-flex align-items-center justify-content-between overflow-hidden">
					<view class="flex-shrink-0">备注</view>
					<navigator hover-class="none" class="flex-fill ml-40 text-truncate text-right" open-type="navigate" url="/pages/pay/remark">{{ remark }}</navigator>
				</view>
		
			</list-cell>
			<list-cell last>
				<view class="w-100 d-flex justify-content-end align-items-center">
					<text class="font-size-sm">共{{ cartNum }}件商品，小计</text>
					<text class="font-size-lg font-weight-bold">￥{{ cartAmount }}</text>
				</view>
			</list-cell>
		</view>
		<list-cell last>
			<view class="w-100 d-flex align-items-center justify-content-between">
				<view>支付方式</view>
				<view class="d-flex align-items-center">
					<image src="/static/images/order/weixin-pay.png" class="wx-pay-icon"></image>
					<view>微信</view>
				</view>
			</view>
		</list-cell>
		<view class="footer">
			<view class="mr-30">
				合计：<text class="font-size-lg font-weight-bold">￥{{ totalPrice }}</text>
			</view>
			<button type="primary" @tap="SubOrder">支付</button>
		</view>
	</view>
</template>

<script>
	import {
		orderConfirm,
		orderCreate
	} from '@/api/waterOrder.js';
	
	import {
		toLogin
	} from '@/libs/login.js';
	
	import listCell from '@/components/list-cell/list-cell.vue';
	import {mapState, mapMutations,mapGetters} from 'vuex';
	
	import {
		openPaySubscribe
	} from '@/utils/SubscribeMessage.js';
	
	export default {
		components: {
			listCell
		},
		data() {
			return {
				cart: uni.getStorageSync('cart'),
				chooseAddress: uni.getStorageSync('chooseAddress'),
				payType: 'weixin', //支付方式
				totalPrice: 0,
				orderKey: "",
				from: 'weixin',
				news: true,
				mark: '' //备注信息
				
			}
		},
		computed: {
			cartNum() {
				return this.cart.reduce((acc, cur) => acc + cur.number, 0)
			},
			cartAmount() {
				return this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0)
			},
			remark() {
				return this.$store.state.app.remark
			},
			address() {
				return this.$store.state.app.address
			},
			isLogin() {
			return !!this.$store.state.app.token	
			}
		},
		
		onLoad: function(options) {			
			// #ifdef H5
			this.from = this.$wechat.isWeixin() ? 'public' : 'weixinh5'
			// #endif
			// #ifdef MP
			this.from = 'routine'
			// #endif
			
			if (this.isLogin) {
				this.getConfirm();
			} else {
				// #ifdef H5 || APP-PLUS
				toLogin();
				// #endif 
				// #ifdef MP
				this.isAuto = true;
				// #endif
			}
				
		},
		
		methods: {
			/**
			 * 获取当前订单详细信息
			 * 
			 */
			getConfirm: function() {
				let that = this,
				data = {};
				data = {
					productVoList: that.cart,
					addressId: that.chooseAddress.id,
					totalPrice: that.cartAmount		
				};
				orderConfirm(data).then(res => {
					that.$set(that, 'orderKey', res.data.orderKey);
					that.$set(that, 'totalPrice',res.data.priceGroup.totalPrice);
				}).catch(err => {
					return this.$util.Tips({
						title: err
					});
				});
			},
		
		   SubOrder: function() {
					let that = this,
					data = {};
					data = {
						addressId: that.chooseAddress.id,
						payType: that.payType,
						mark: that.mark,
					    'from': that.from,
						isNew: that.news
					};
					 
					uni.showLoading({
						title: '订单支付中'
					});
					// #ifdef MP
					openPaySubscribe().then(() => {
						that.payment(data);
					});
					// #endif
					// #ifndef MP
					console.log(1111);
					console.log(data);
					that.payment(data);
					// #endif
				},
		
			payment: function(data) {
				let that = this;
				orderCreate(that.orderKey, data).then(res => {
					let result = res.data.result,
						status = res.data.status,
						orderId = result.orderId,
						jsConfig = res.data.jsConfig,
						message = res.data.message;
						
						console.log(status);
						if(that.news == "false"){
							orderPay({
								'paytype': that.payType,
								'uni':res.data.result.key,
								// #ifdef MP 
								'from': 'routine',
								// #endif
								// #ifdef H5 || APP-PLUS
								'from': this.$wechat.isWeixin() ? 'weixin' : 'weixinh5',
								// #endif
							}).then(res=>{
								result = res.data.result;
								status = res.data.status;
								orderId = result.orderId;
								jsConfig = res.data.jsConfig;
								message = res.data.message;
								that.getPayType(status,orderId,message,jsConfig);
							})
						}else{
							that.getPayType(status,orderId,message,jsConfig);
						}
				}).catch(err => {
					uni.hideLoading();
					return that.$util.Tips({
						title: err
					});
				});
			},
			
			getPayType: function(status,orderId,message,jsConfig){
				let that = this;
				let goPages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=' + message;
				switch (status) {
					case 'ORDER_EXIST':
					case 'EXTEND_ORDER':
					case 'PAY_ERROR':
						uni.hideLoading();
						return that.$util.Tips({
							title: message
						}, {
							tab: 5,
							url: goPages
						});
						break;
					case 'SUCCESS':	
						uni.hideLoading();
						if (that.BargainId || that.combinationId || that.pinkId || that.seckillId)
							return that.$util.Tips({
								title: message,
								icon: 'success'
							}, {
								tab: 4,
								url: goPages
							});	
						return that.$util.Tips({
							title: message,
							icon: 'success'
						}, {
							tab: 5,
							url: goPages
						});
						break;
					case 'WECHAT_PAY':
						// #ifdef MP
						that.toPay = true;
						let packages = 'prepay_id=' + jsConfig.prepayId;
						uni.requestPayment({
							timeStamp: jsConfig.timeStamp.toString(),
							nonceStr: jsConfig.nonceStr,
							package: packages,
							signType: jsConfig.signType,
							paySign: jsConfig.paySign,
							success: function(res) {
								uni.hideLoading();
								if (that.BargainId || that.combinationId || that.pinkId || that.seckillId)
									return that.$util.Tips({
										title: '支付成功',
										icon: 'success'
									}, {
										tab: 4,
										url: goPages
									});
								return that.$util.Tips({
									title: '支付成功',
									icon: 'success'
								}, {
									tab: 5,
									url: goPages
								});
							},
							fail: function(e) {
								uni.hideLoading();
								return that.$util.Tips({
									title: '取消支付'
								}, {
									tab: 5,
									url: goPages + '&status=0'
								});
							},
							complete: function(e) {
								uni.hideLoading();
								//关闭当前页面跳转至订单状态
								if (res.errMsg == 'requestPayment:cancel') return that.$util.Tips({
									title: '取消支付'
								}, {
									tab: 5,
									url: goPages + '&status=0'
								});
							},
						})
						// #endif
						// #ifdef H5
						let jsConfigAgain = jsConfig;
						let packages = 'prepay_id=' + jsConfigAgain.prepayId;
						let data = {
							timestamp:jsConfigAgain.timeStamp,
							nonceStr:jsConfigAgain.nonceStr,
							package:packages,
							signType:jsConfigAgain.signType,
							paySign:jsConfigAgain.paySign,
							h5PayUrl:jsConfigAgain.h5PayUrl
						};
						this.$wechat.pay(data).then(res => {
							return that.$util.Tips({
								title: '支付成功',
								icon: 'success'
							}, {
								tab: 5,
								url: goPages
							});
						}).cache(res => {
							if (res.errMsg == 'requestPayment:cancel') return that.$util.Tips({
								title: '取消支付'
							}, {
								tab: 5,
								url: goPages + '&status=0'
							});
						})
						// #endif
						break;
					case 'PAY_DEFICIENCY':
						uni.hideLoading();
						//余额不足
						return that.$util.Tips({
							title: message
						}, {
							tab: 5,
							url: goPages + '&status=1'
						});
						break;
					case "WECHAT_H5_PAY": //网页版公众号支付
						setTimeout(() => {
							let domain = encodeURIComponent(location.href);
							let urls = jsConfigAgain.h5PayUrl + '&redirect_url='+ domain;
							location.href = urls;
							return that.$util.Tips({
								title: '支付成功',
								icon: 'success'
							}, {
								tab: 5,
								url: goPages
							});
						}, 100);
						break;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import url("@/static/css/main.css");
	
	
	.container {
		height: auto;
		padding-bottom: 120rpx;
	}
	
	.pro-img {
		width: 120rpx;
		height: 90rpx;
		flex-shrink: 0;
	}
	
	.coupon-label {
		background-color: $color-primary;
		color: #FFFFFF;
		font-size: 18rpx;
		line-height: 0.9rem;
		width: 0.9rem;
		height: 0.9rem;
		margin-left: 10rpx;
		text-align: center;
	}
	
	.wx-pay-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}
	
	.footer {
		background-color: #FFFFFF;
		z-index: 10;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		
		button {
			width: 250rpx;
			text-align: center;
			padding: 0;
			height: 100%;
			line-height: 100rpx;
			border-radius: 0 !important;
			font-size: $font-size-lg;
		}
	}
	button {
		background-color: $color-primary;
	}
</style>
